﻿using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace Autorun
{
	public delegate void ConnectServerEventHandler(object sender, ConnectServerEventArgs e);

	public partial class PaneRegisteredServers : Autorun.PaneBase
	{
		public event ConnectServerEventHandler OnConnectServer;

		private const string ROOT_NODE = "ROOT";
		#region "Constructors"
		public PaneRegisteredServers()
		{
			InitializeComponent();
		}
		#endregion

		#region "Form Event Handlers"
		private void PaneRegisteredServers_Load(object sender, EventArgs e)
		{
			// === Set the look and feel ===========================================
			LoadIcons();
			LoadRegisteredServers();
			myTree.ExpandAll();
		}

		private void myTree_DoubleClick(object sender, EventArgs e)
		{
			string query;
			DataTable dt;

			if (myTree.SelectedNode.Name != ROOT_NODE)
				if (myTree.SelectedNode.Name == "0")
					OnConnectServer(this, new ConnectServerEventArgs());
				else
				{
					query = string.Format("SELECT * FROM tblServer WHERE svrId={0}", myTree.SelectedNode.Name);
					dt = ExecuteDataTable(query);
					if (dt.Rows.Count > 0)
						OnConnectServer(this, new ConnectServerEventArgs(dt.Rows[0]["svrHost"].ToString(), (int)dt.Rows[0]["svrPort"], dt.Rows[0]["svrChannel"].ToString()));
				}
		}

		private void myTree_MouseDown(object sender, MouseEventArgs e)
		{
			myTree.SelectedNode = myTree.HitTest(e.X, e.Y).Node;
		}

		private void myPopup_Opening(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if (myTree.SelectedNode == null)
				mnuUnregister.Enabled = false;
			else
				mnuUnregister.Enabled = ((myTree.SelectedNode.Name != ROOT_NODE) && (myTree.SelectedNode.Name != "0"));
		}

		private void mnuUnregister_Click(object sender, EventArgs e)
		{
			string query;

			if ((myTree.SelectedNode.Name != ROOT_NODE) && (myTree.SelectedNode.Name != "0"))
			{
#if !DEBUG
				if (MessageBox.Show(string.Format("Are you sure you want to delete the registered server '{0}'?", myTree.SelectedNode.Text), Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
#endif
				query = string.Format("DELETE FROM tblServer WHERE svrId={0}", myTree.SelectedNode.Name);
				ExecuteNonQuery(query);
				LoadRegisteredServers();
#if !DEBUG
				}
#endif
			}

		}
		#endregion

		#region "Private methods"
		private void LoadIcons()
		{
			myImages.Images.Clear();
			myImages.Images.Add(Properties.Resources.icoRegisteredServers);
			myImages.Images.Add(Properties.Resources.icoConnectedServer);
		}

		public void LoadRegisteredServers()
		{
			TreeNode root;
			string query;
			DataTable dt;

			// === Add default nodes ===============================================
			myTree.Nodes.Clear();
			root = myTree.Nodes.Add(ROOT_NODE, "Registered Servers", 0, 0);
			root.Nodes.Add("0", "(Built-In Server)", 1, 1);

			// === Add registered servers ==========================================
			if (DesignMode == true) return;
			query = "SELECT * FROM tblServer ORDER BY svrHost";
			dt = ExecuteDataTable(query);
			foreach (DataRow dr in dt.Rows)
				root.Nodes.Add(dr["svrId"].ToString(), dr["svrHost"].ToString(), 1, 1);

			myTree.ExpandAll();
		}
		#endregion

		#region "Data Access Methods"
		private void ExecuteNonQuery(string query)
		{
			SqlConnection cn;
			SqlCommand cmd;

			cn = new SqlConnection(Properties.Settings.Default.ConnectionString);

			try
			{
				cn.Open();
				cmd = cn.CreateCommand();
				cmd.CommandText = query;
				cmd.ExecuteNonQuery();
				cmd.Connection = null;
				cmd = null;
			}
			finally
			{
				cn.Close();
			}
		}

		private object ExecuteScalar(string query)
		{
			SqlConnection cn;
			SqlCommand cmd;
			object rc = null;

			cn = new SqlConnection(Properties.Settings.Default.ConnectionString);

			try
			{
				cn.Open();
				cmd = cn.CreateCommand();
				cmd.CommandText = query;
				rc = cmd.ExecuteScalar();
				cmd.Connection = null;
				cmd = null;
			}
			finally
			{
				cn.Close();
			}

			return rc;
		}

		private DataTable ExecuteDataTable(string query)
		{
			SqlDataAdapter da;
			DataSet rc;

			da = new SqlDataAdapter(query, Properties.Settings.Default.ConnectionString);
			rc = new DataSet();
			da.Fill(rc);
			return rc.Tables.Count != 0 ? rc.Tables[0] : null;
		}
		#endregion

	}
}
